﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Store.Manager.ERP.Application.Dtos;
using Store.Manager.ERP.Application.Services;

namespace StoreManager.ERP.Api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly IProductService _productService;

        public ProductController(IProductService productService)
        {
            _productService = productService;
        }

        [HttpPost()]
        public async Task<IActionResult> AddProduct([FromBody] ProductDto productDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var addedProduct = await _productService.AddProductAsync(productDto);
            return CreatedAtAction(nameof(GetProductByCode), new { code = addedProduct.Code }, addedProduct);
        }

        [HttpPost]
        public async Task<IActionResult> AddProducts([FromBody] List<ProductDto> productDtos)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var addedProducts = await _productService.AddProductsAsync(productDtos);
            return Ok(addedProducts);
        }

        [HttpPut]
        public async Task<IActionResult> UpdateProduct([FromBody] ProductDto productDto)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            await _productService.UpdateProductAsync(productDto);
            return NoContent();
        }

        [HttpDelete("{code}")]
        public async Task<IActionResult> DeleteProduct(string code)
        {
            await _productService.DeleteProductAsync(code);
            return NoContent();
        }

        [HttpGet("{code}")]
        public async Task<IActionResult> GetProductByCode(string code)
        {
            var productDto = await _productService.GetProductByCodeAsync(code);
            if (productDto == null)
            {
                return NotFound();
            }
            return Ok(productDto);
        }

        [HttpGet]
        public async Task<IActionResult> GetAllProducts()
        {
            var products = await _productService.GetAllProductsAsync();
            return Ok(products);
        }
    }
}
